const express = require('express');
const router = express.Router();
const Nonogram = require('../models/Nonogram');

let gameInstance = null;

// 创建新游戏
router.post('/new-game', (req, res) => {
    try {
        const size = Math.min(Math.max(parseInt(req.body.size) || 5, 5), 15);
        gameInstance = new Nonogram(size, size);
        
        const gameState = gameInstance.getGameState();
        const isValid = validateGameState(gameState);
        
        if (!isValid) {
            gameInstance = new Nonogram(size, size);
            gameState = gameInstance.getGameState();
        }
        
        gameState.solution = gameInstance.solution;
        
        console.log('新游戏已创建:', { size, gameState });
        res.json(gameState);
    } catch (error) {
        console.error('创建游戏失败:', error);
        res.status(400).json({ error: '创建新游戏失败', details: error.message });
    }
});

// 检查答案
router.post('/check-solution', (req, res) => {
    try {
        if (!gameInstance) {
            return res.status(400).json({ error: '没有正在进行的游戏' });
        }
        
        const playerGrid = req.body.grid;
        if (!Array.isArray(playerGrid)) {
            return res.status(400).json({ error: '无效的游戏数据' });
        }

        const isCorrect = gameInstance.checkWin(playerGrid);
        console.log('检查答案:', { isCorrect, playerGrid });
        
        res.json({
            correct: isCorrect,
            solution: isCorrect ? gameInstance.solution : null,
            timePlayed: Math.floor((Date.now() - gameInstance.startTime) / 1000)
        });
    } catch (error) {
        console.error('检查答案失败:', error);
        res.status(400).json({ error: '检查答案失败', details: error.message });
    }
});

// 验证游戏数据
function validateGameState(gameState) {
    // 检查行提示
    const validRows = gameState.rowHints.every(hints => 
        hints.length > 0 && hints.every(h => h > 0)
    );
    
    // 检查列提示
    const validCols = gameState.colHints.every(hints => 
        hints.length > 0 && hints.every(h => h > 0)
    );
    
    return validRows && validCols;
}

module.exports = router; 